/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cs;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

/**
 *
 * @author QuangHieu
 */
public class MyHashTable {

    String ht[];
    final int size = 101;
    int num;

    public MyHashTable() {
        ht = new String[size];
        num = 0;
    }

    int hash(String t) {
        int d = 0;
        for (int i = 0; i < t.length(); i++) {
            d = d + (int) t.charAt(i);
        }
        return d % size;
    }

    void load(String fileName) throws FileNotFoundException {
        try {
            FileReader fr = new FileReader(fileName);
            Scanner k = new Scanner(fr);
            while (k.hasNext()) {
                String t = k.next();
                insert(t);
            }
        } catch (java.io.FileNotFoundException e) {
            System.out.print(e.getMessage());
        } catch (IOException o) {
            System.out.print(o.getMessage());
        }
    }

    void insert(String t) {
        if (num < size) {
            int vt = hash(t);
            while (true) {
                if (ht[vt] == null) {
                    ht[vt] = t;
                    num++;
                    break;
                }else if (ht[vt].endsWith(t)) 
                    break;
                 else
                    vt = (vt + 1) % size;          
           }
        } else 
            System.out.print("\nBang Bam Da Day");
    }

    public String toString() {
        String t = "{";
        for (int i = 0; i < size; i++) {
            if (i % 10 == 0) 
                t = t + "\n";
            t = t + "[" + i + ",";
            if (ht[i] != null) 
                t = t + ht[i] + "];    ";
            else
                t = t + " " + "];    ";
        }
        t = t + "\n}\n";
        return t;
    }

    public static void main(String args[]) throws IOException {
        MyHashTable t = new MyHashTable();
        //t.insert("for");
        //t.insert("printed");
        //t.insert("ha");
        String s = "E:\\FileText\\CS.txt";
        t.load(s);
        System.out.print("\nBang bam la:\n" + t);
    }
}
